package com.mes.handler;

import com.mes.data.EmesPBom;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.openbravo.base.exception.OBException;
import org.openbravo.client.kernel.BaseActionHandler;
import org.openbravo.dal.service.OBDal;

import java.util.Map;

public class PbomAuditHandler extends BaseActionHandler {
	@Override
	protected JSONObject execute(Map<String, Object> parameters, String data) {
		JSONObject jsonRep = new JSONObject();
		try {
			JSONObject jsonData = new JSONObject(data);
			String id = jsonData.getString("recordId");
			String type = jsonData.getString("type");
			
			EmesPBom pbom = OBDal.getInstance().get(EmesPBom.class, id);
			
			if ("audit".equals(type)) {
				pbom.setAudit(true);
				jsonRep.put("msg", "审核成功！");
			} else if ("default".equals(type)) {
				/*String hql = "update Emes_PBOM set default = false where product.id = '" + pbom.getProduct().getId() + "'";
				OBDal.getInstance().getSession().createQuery(hql).executeUpdate();
				*/
				pbom.setDefault(true);
				jsonRep.put("msg", "设置默认成功！");
			}
			OBDal.getInstance().save(pbom);
			jsonRep.put("result", true);

			OBDal.getInstance().commitAndClose();
		} catch (Exception e) {
			OBDal.getInstance().rollbackAndClose();
			try {
				jsonRep.put("result", false);
				jsonRep.put("msg", "处理失败！");
			} catch (JSONException e1) {
			}
			throw new OBException(e);
		}
		return jsonRep;
	}
}
